<html>
<body>
<h1>Movie Database</h1>
<p>Please enter your query in the following box:</p>
<form method="get">
	<textarea name="query" cols="60" rows="8"></textarea>
	<input type="submit" value="Submit" />
</form>
<small>Note: tables and fields are case sensitive. Run \"show tables\" to see the list of available tables.</small><br />
<?php
	if(isset($_GET["query"])&&$_GET["query"]!=""&&preg_match("/^(\s*)(SELECT|SHOW)/i",$_GET["query"]))
	{
		echo "<h2>MySQL Result:</h2>";
		$input = $_GET["query"];
		$dbcon = mysql_connect("localhost", "cs143","") or die("Unable to connect to SQL server ".mysql_error()."<br />");
		$con = mysql_select_db("CS143",$dbcon) or die("Unable to connect to database ".mysql_error()."<br />");
		$sanname = mysql_real_escape_string($name, $dbcon);
		$secquery = sprintf($input, $sanname);
		$fquery = mysql_query($secquery,$dbcon) or die ("Query error ".mysql_error()."<br />");
		$numfields = mysql_num_fields($fquery);
		echo '<table border="1"><tr>';
		for ($i = 0; $i<$numfields; $i ++) {
			$field = mysql_fetch_field($fquery, $i);
			echo '<th>' . $field->name . '</th>';
		}
		echo '</tr>';
		while ($fielddata = mysql_fetch_array($fquery)) {
			echo '<tr>';
			for ($j = 0; $j<$numfields; $j ++) {
				$field = mysql_fetch_field($fquery, $j);
				echo '<td>' . $fielddata[$field->name] . '</td>';
			}
			echo '</tr>';
		}
		echo '</table>';   
		mysql_free_result($fquery);
		$close =  mysql_close($dbcon) or die ("Unable to SQL connection ".mysql_error()."<br />");
	}
	else if(isset($_GET["query"])&&$_GET["query"]=="")
		echo "Please enter a query.";
	else if(isset($_GET["query"])&&$_GET["query"]!= "")
		echo "<br>Sorry, only SELECT and SHOW queries are allowed!";
?>

</body>
</html>